//
//  PartyRefreshController.m
//  UESTCPioneer
//
//  Created by Apple on 14-9-26.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "PartyRefreshController.h"
#import "PioneerNewsEntity.h"
#import "UPTitleCell.h"
#import "UPMainInfoCell.h"
#import "UPFooterCell.h"
#import "PartyFullContentController.h"
#import "PartyCleanCutureEntity.h"
#import "NewsDetailViewController.h"

static NSString *customTitleCellIndentifier = @"CustomTitleCellIndentifier";
static NSString *customMainCellIndentifier = @"CustomMainCellIndentifier";
static NSString *customFooterCellIndentifier = @"CustomFooterCellIndentifier";
@interface PartyRefreshController ()<UPMainInfoCellDelegate,UPTitleCellDelegate,UPFooterCellDelegate>
{
    NSMutableDictionary *_cellHeightDictionary;
}

@end

@implementation PartyRefreshController

-(void)_initRequestRequireEntityName:(NSString*)EntityName EntityMapping:(NSDictionary*)EntityMapping RequestData:(NSDictionary*)RequestData CommentListRequestData:(NSDictionary*)CommentListRequestData CommentWriteRequestData:(NSDictionary*)CommentWriteRequestData CommentIdKey:(NSString*)CommentIdKey CommentContentKey:(NSString*)CommentContentKey CommentListKeyMapping:(NSDictionary*)CommentListKeyMapping{
    
    entityName=EntityName;
    entityMapping=EntityMapping;
    requestData=RequestData;
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self.tableView registerClass:[UPTitleCell class] forCellReuseIdentifier:customTitleCellIndentifier];
    [self.tableView registerClass:[UPMainInfoCell class] forCellReuseIdentifier:customMainCellIndentifier];
    [self.tableView registerClass:[UPFooterCell class] forCellReuseIdentifier:customFooterCellIndentifier];
    _cellHeightDictionary=[[NSMutableDictionary alloc]init];
    //@AGPhotoBrowser
//    AGPhotoBrowserView *photoBrowser = [[AGPhotoBrowserView alloc]init];
}

#pragma mark - refresh request
-(void)pullDownRefresh:(MJRefreshBaseView *)refreshView{
    [PublicMethod ClearEntity:entityName];
    [NetworkCenter RKRequestWithData:requestData EntityName:entityName Mapping:entityMapping SuccessBlock:^(NSArray *resultArray) {
        NSMutableArray *dic = [[NSMutableArray alloc]init];
        [dic addObjectsFromArray:resultArray];
        tableViewEntitiesArray=[[NSArray alloc]initWithArray:dic];
        [self.tableView reloadData];
        PullUpRefreshTimes=0;
        [refreshView endRefreshing];
    } failure:^(NSError *error) {
        [refreshView endRefreshing];
        [Alert showAlert:@"刷新失败!"];
    }];
}

-(void)pullUpRefresh:(MJRefreshBaseView *)refreshView{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:requestData];
    [dic setObject:[NSString stringWithFormat:@"%d",PullUpRefreshTimes+2] forKey:@"page"];

    [NetworkCenter RKRequestWithData:dic EntityName:entityName Mapping:entityMapping SuccessBlock:^(NSArray *resultArray) {
        
        if ([resultArray count]==0){
            [refreshView endRefreshing];
            return ;
        }
        
        NSMutableArray *newArray = [[NSMutableArray alloc]init];
        [newArray addObjectsFromArray:tableViewEntitiesArray];
        [newArray addObjectsFromArray:resultArray];
        NSArray *result = [[NSArray alloc]initWithArray:newArray];

        tableViewEntitiesArray=result;
        [self.tableView reloadData];
        
        //清除core data 因为现在还没有适合下拉刷新和适合本地缓存的api
        
        [refreshView endRefreshing];
        PullUpRefreshTimes++;
        
    } failure:^(NSError *error) {
        [Alert showAlert:@"刷新失败！"];
        [refreshView endRefreshing];
    }];
}

#pragma mark - 全文按钮事件
-(BOOL)ScreenTouch{
    return NO;
}

-(void)WholeNewsButtonClick:(NSInteger)theId{
    BOOL result = [self ScreenTouch];
    if (result) {
        return;
    }
    
    PartyCleanCutureEntity *entity = [PublicMethod entity:@"PartyCleanCutureEntity" WithId:theId];
    
    
    NSString *content;
    content =entity.content;

    NSDictionary *pic=entity.picUrl;
    NSArray *ImageUrlArray=[pic allValues];
    NSLog(@"entity = %@",entity);
    
    NewsDetailViewController * viewController = [[NewsDetailViewController alloc] initWithImgUrlArr:ImageUrlArray title:entity.title content:content];
    [viewController.view setFrame:self.view.frame];
    
    [self.leveyTabBarController.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - tableView Cell dequeue
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PartyCleanCutureEntity *entity= tableViewEntitiesArray[indexPath.section];
    if (indexPath.row == 0) {
        //6.0后用这种方式更直接，可以省掉if（cell2＝＝nil）的判断   @黄卓越 2014-3-28
        UPTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:customTitleCellIndentifier forIndexPath:indexPath];
        cell.theId=[entity.theId integerValue];
        [cell setTitle:entity.title];
        [cell setTime:entity.time];
        
        cell.indexPath = indexPath;

        return cell;
    }
    else {
        //6.0后用这种方式更直接，可以省掉if（cell2＝＝nil）的判断   @黄卓越 2014-3-28
        UPMainInfoCell *cell2 = [tableView dequeueReusableCellWithIdentifier:customMainCellIndentifier forIndexPath:indexPath];;
        NSDictionary *pic=entity.picUrl;
        NSArray *ImageUrlArray=[pic  allValues];
        
        
        NSMutableArray *temp = [[NSMutableArray alloc]init];
        for (NSString *suffix in ImageUrlArray){
            [temp addObject:[baseUrl stringByAppendingString:suffix]];
        }
        
        NSArray *urlArray = [[NSArray alloc]initWithArray:temp];
        
        
        [cell2 setImageUrlArray:urlArray];
        //@cell的高度自适应
        if ([cell2 hasImage])_cellHeightDictionary[@(indexPath.section)]=@(110+imageViewWidth);
        else _cellHeightDictionary[@(indexPath.section)]=@(110);
        [cell2 setNewsBody:entity.content];
        cell2.theId=[entity.theId integerValue];
        cell2.delegate=self;
        return cell2;
    }
//    else {
//        UPFooterCell * cell3;
//        cell3 = [tableView dequeueReusableCellWithIdentifier:customFooterCellIndentifier forIndexPath:indexPath];
//        
//        /*修改*/
//        for (UIView * view in  cell3.contentView.subviews) {
//            if (view.tag == 100) {
//                [view removeFromSuperview];
//            }
//        }
//        /**/
//        
//        cell3.theId=[entity.theId integerValue];
//        cell3.delegate=self;
//        UIButton *btn1 = (UIButton *)[cell3.contentView viewWithTag:btn1Tag];
//        
//        /*微党课-党课资料*/
//        [cell3 setCommentVisiable:NO];
////        [cell3 setDownloadVisiable:NO];
//        
//        /*微党课-党课资料*/
//        if (self.fromSourceEnable) {
//            [cell3 setFromSourceStatus:YES fromSource:self.source];
//        }
//        [btn1 setImage:[UIImage imageNamed:@"read.png"] forState:UIControlStateNormal];
//        return cell3;
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 55;
    }
    else if (indexPath.row == 1){
        
        //判断是否有图片以适应高度
        CGFloat height;
        
        NewsEntity *entity =tableViewEntitiesArray[indexPath.section];
        NSDictionary *picDic= entity.picUrl;
        NSInteger imageNum=[picDic count];
        if (imageNum==0){
            height=110;
        }
        else {
            if (imageNum==1){
                height=110+imageViewWidth+120;
            }
            else if (imageNum==2){
                height=110+imageViewWidth+90;
            }
            else if (imageNum==3){
                height=110+imageViewWidth+60;
            }
            else {
                height=110+imageViewWidth+30;
            }
        }
        return height;
    }
    else
        return 40;
}


-(void)downloadButtonClick:(commentButton *)btn{
    NSLog(@"下载%i文件",btn.theId);
}

@end
